<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @sort-change="sortChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   effect="dark"
                   v-if="permission.wa_service_task_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-divider direction="vertical" />
      </template>

      <template #menu-form-before="{ size }">
        <el-tooltip
          effect="dark"
          content="不指定代理国家则使用随机国家"
          placement="left-start">
          <el-button color="#626aef"
                     icon="el-icon-location-information"
                     effect="dark"
                     @click="checkIp">IP检测
          </el-button>
        </el-tooltip>
        <el-divider direction="vertical" />
      </template>

      <template #countryMappingId="{ row }">
        <el-tag effect="dark" size="small">{{ row.$countryMappingId }}</el-tag>
      </template>
      <template #deviceType="{ row }">
        <el-text type="primary" size="small">{{ row.$deviceType }}</el-text>
      </template>
      <template #updateUser="{ row }">
        <el-text size="small">{{ row.updateUserName }}</el-text>
      </template>
      <template #status="{ row }">
        <el-switch
          v-model="row.status"
          inline-prompt
          @change="statusChange(row)"
          active-text="启用"
          inactive-text="暂停"
          :active-value="1"
          :inactive-value="0"
        />
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/whatsapp/service-task';
import { getApiOption } from '@/api/sms/service-api';
import { getDetail as getCountryById } from '@/api/country/country-manage';
import { checkIp } from '@/api/whatsapp/ip-check';
import option from '@/option/whatsapp/service-task';
import { mapGetters } from 'vuex';
import func from '@/utils/func';

export default {
  data() {
    return {
      form: {},
      query: {},
      sort: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option(this),
      data: []
    };
  },
  props: {
    serviceApiId: String,
    serviceConfigId: String
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.wa_service_task_add, false) && this.serviceConfigId !== undefined,
        viewBtn: this.validData(this.permission.wa_service_task_view, false),
        delBtn: this.validData(this.permission.wa_service_task_delete, false),
        editBtn: this.validData(this.permission.wa_service_task_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.sort.descs = 'update_time';
    if (!this.serviceApiId) {
      this.findObject(this.option.column, 'serviceConfigId').search = true;
      let serviceApiIdOption = this.findObject(this.option.column, 'serviceApiId');
      serviceApiIdOption.search = true;
      serviceApiIdOption.cascader = ['countryMappingId'];
      this.findObject(this.option.column, 'countryMappingId').dicQuery = { serviceApiId: `{{serviceApiId}}` };

      let smsGroupOption = this.findObject(this.option.group, 'smsGroup');
      this.findObject(smsGroupOption.column, 'serviceApiId').cascader = ['countryMappingId'];
      this.findObject(smsGroupOption.column, 'countryMappingId').dicQuery = { serviceApiId: `{{serviceApiId}}` };
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['add', 'edit'].includes(type)) {
        getApiOption(this.serviceApiId || this.query.serviceApiId).then(res => {
          let option = res.data.data;
          this.findObject(smsGroupOption.column, 'maxPrice').disabled = option.isMaxPrice === 2;
          this.findObject(smsGroupOption.column, 'phoneException').disabled = option.isPhoneException === 2;
          let findObject = this.findObject(smsGroupOption.column, 'operatorArray');
          findObject.type = option.isOperatorArray === 1 ? 'radio' : 'checkbox';
          findObject.rules = '5sim' === option.service ? [{ required: true, message: '请选择运营商', trigger: 'blur' }] : [];
        });
      }
      let smsGroupOption = this.findObject(this.option.group, 'smsGroup');
      if (['edit', 'view'].includes(type)) {
        if (this.serviceApiId) {
          this.findObject(smsGroupOption.column, 'countryMappingId').disabled = true;
          // this.findObject(smsGroupOption.column, 'countryMappingId').dicQuery = { serviceApiId: this.$props.serviceApiId };
        }
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      } else {
        if (this.serviceApiId) {
          this.form.serviceApiId = this.serviceApiId;
          this.findObject(smsGroupOption.column, 'countryMappingId').disabled = false;
          // this.findObject(smsGroupOption.column, 'countryMappingId').dicQuery = { serviceApiId: this.$props.serviceApiId, serviceConfigId: this.$props.serviceConfigId };
        }
        if (this.serviceConfigId) {
          this.form.serviceConfigId = this.serviceConfigId;
        }
      }

      done();
    },
    searchReset() {
      this.query = {};
      this.data = [];
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      this.sort = {};
      if (func.notEmpty(val.order)) {
        if (val.order === 'ascending') {
          this.sort.ascs = func.cameCaseToLine(val.prop);
        } else {
          this.sort.descs = func.cameCaseToLine(val.prop);
        }
      }
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      if (!this.serviceApiId && !this.query.serviceApiId) {
        this.loading = false;
        this.$message.warning('请选择接码平台');
        return;
      }

      if (this.serviceConfigId) {
        params.serviceConfigId = this.serviceConfigId;
      }

      const {
        serviceApiId,
        serviceConfigId,
        countryMappingId,
        status
      } = Object.assign(params, this.query);

      let values = {
        serviceApiId_equal: serviceApiId,
        serviceConfigId_equal: serviceConfigId,
        countryMappingId_equal: countryMappingId,
        status_equal: status
      };

      getList(page.currentPage, page.pageSize, this.sort, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.$nextTick(() => {
          //放在数据加载完后执行
          this.$refs.crud.dicInit('cascader');
        });
      });
    },
    statusChange(row) {
      if (!row.id) {
        return;
      }
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    checkIp() {
      if (func.isEmpty(this.form.proxyId)) {
        this.$message.warning('请选择代理');
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '请求中,请稍后...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (func.isEmpty(this.form.proxyCountryId)) {
        checkIp(this.form.proxyId, null).then(res => {
          this.$message({
            showClose: true,
            duration: 30000,
            type: 'success',
            message: res.data.data
          });
          loading.close();
        });
      } else {
        getCountryById(this.form.proxyCountryId).then(res => {
          let countryCode = res.data.data.code;
          checkIp(this.form.proxyId, countryCode).then(res => {
            this.$message({
              showClose: true,
              duration: 30000,
              type: 'success',
              message: res.data.data
            });
            loading.close();
          });
        });
      }
    }
  }
};
</script>

<style>
.transfer-footer {
  margin-left: 15px;
  padding: 6px 5px;
}
</style>
